#include "stdafx.h"
#include "ImageButton.h"

using namespace AirCrash::Calypso;

ImageButton::ImageButton(QWidget * parent) : QAbstractButton(parent), mMouseButtonDown(false), mMouseOnButton(false) {
}
ImageButton::~ImageButton() {
}

void ImageButton::paintEvent(QPaintEvent * e) {
	QPainter painter(this);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::HighQualityAntialiasing);

	if (isEnabled()) {
		if (mMouseButtonDown) {
			painter.drawImage(rect(), mPressedImage);
		} else if (mMouseOnButton) {
			painter.drawImage(rect(), mHoverImage);
		} else {
			painter.drawImage(rect(), mNormalImage);
		}
	} else {
		painter.drawImage(rect(), mDisabledImage);
	}
}

void ImageButton::enterEvent(QEvent * e) {
	mMouseOnButton = true;
	repaint();
}

void ImageButton::leaveEvent(QEvent * e) {
	mMouseOnButton = false;
	repaint();
}

void ImageButton::mousePressEvent(QMouseEvent * e) {
	QAbstractButton::mousePressEvent(e);
	mMouseButtonDown = true;
	repaint();
}

void ImageButton::mouseReleaseEvent(QMouseEvent * e) {
	QAbstractButton::mouseReleaseEvent(e);
	mMouseButtonDown = false;
	repaint();
}

void ImageButton::setImages(const QString& category, const QString& name) {
	mNormalImage = QImage(Config::get(category, name + "Normal").toString());
	
	QString hoverImage(Config::get(category, name + "Hover").toString()),
		pressedImage(Config::get(category, name + "Pressed").toString());

	hoverImage.isEmpty() ? mHoverImage = mNormalImage : mHoverImage = QImage(hoverImage);
	hoverImage.isEmpty() ? mPressedImage = mNormalImage : mPressedImage = QImage(pressedImage);
	mDisabledImage = makeGrayScaleImage(mNormalImage);	
}
